package com.wlit;

import gnu.io.*;
import io.netty.buffer.ByteBufUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class SerialTest {

    private static SerialPort theSerialPort;
    private  static OutputStream theOut;

    public static void main(String[] args) throws Exception {
        init();
        write();

        Thread.sleep(2000);
        close();
    }

    public static void init()  {
        try {
            String portName = "COM3";
            CommPortIdentifier commPortIdentifier = CommPortIdentifier.getPortIdentifier(portName);

            CommPort commPort = commPortIdentifier.open(portName, 5000);

            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            serialPort.notifyOnDataAvailable(true);
            InputStream inputStream = serialPort.getInputStream();
            OutputStream outputStream = serialPort.getOutputStream();
            serialPort.addEventListener(new SerialPortEventListener() {
                @Override
                public void serialEvent(SerialPortEvent p0) {
                    if (p0.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                        Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name());
                        while (scanner.hasNextLine()) {
                            String line = scanner.nextLine();
                            System.out.println(line);
                        }
                    }
                }
            });
            theSerialPort = serialPort;
            theOut = outputStream;
        }catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void write(){
        try {
            /**
             * 这串数据来自YsMaker来生成
             */
            byte[] bb = ByteBufUtil.decodeHexDump("0110001000050A0003001E010100020201A7A8");
            System.out.println(ByteBufUtil.hexDump(bb));
            theOut.write(bb);
            theOut.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void close(){
        theSerialPort.close();
    }
}
